//
//  HBShakeGamesCtrl.m
//  HuoBao
//
//  Created by 于会海 on 15/12/10.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "HBShakeGamesCtrl.h"
#import "LZAudioTool.h"
#import "HBShakeResultCtrl.h"
#import "HBUserShakeRedInfo.h"
#import "HBUserShakeRedParam.h"
#import "HBUserShakeRedParser.h"
#import "ShakePushTransition.h"
#import "HBLoginManager.h"
#import "HBGetRedManager.h"
#import "CustomerShakeRule.h"
#import <AudioToolbox/AudioToolbox.h>

@interface HBShakeGamesCtrl ()
<UINavigationControllerDelegate>
{
    
    LZAudioTool*     tool;
    NSInteger        firstShakeCount;
    NSInteger        shakeCount;
    UIButton*        botTapBtn;
    UIButton*        gameStartBtn;
    UIImageView*     actvRuleImage;
    UIImageView*     botOrangeView;
    UIImageView*     botOrangeShadow;
    UIImageView*     shakeImageView;
    UIImageView*     gameStartBtnImage;
    UIImage*         thirdImage;
    NSArray*         orangeArr;
    NSMutableArray*  childImageArr;
    NSMutableArray*  actRuleArr;
    NSMutableArray*  shakeImageArr;
    CGPoint          orginPoint;
    BOOL             isStart;
    BOOL             isShowRuleView;
    BOOL             isCancelRuleView;
    UIView* backView;
    UILabel* label[4];
}
@property (weak, nonatomic) IBOutlet UIImageView *backImage;
@property (weak, nonatomic) IBOutlet UIView *basicView;
@property (weak, nonatomic) IBOutlet UIImageView *topTitleView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topTitleViewLeadingToTop;
@property (weak, nonatomic) IBOutlet UIImageView *firstOrange;
@property (weak, nonatomic) IBOutlet UIImageView *secOrange;
@property (weak, nonatomic) IBOutlet UIImageView *thirdOrange;
@property (weak, nonatomic) IBOutlet UIImageView *fourthOrange;
@property (weak, nonatomic) IBOutlet UIImageView *fifthOrange;
@property (weak, nonatomic) IBOutlet UIImageView *sixOrange;
@property (weak, nonatomic) IBOutlet UIImageView *seventhOrange;
@property (weak, nonatomic) IBOutlet UIImageView *eitOrange;

#define GetFinalresult(a,b) (IsIphone4?a:b)
#define GetFinalResult(x,y,z,r) (IsIphone4?x:(IsIphone6P?r:(IsIphone5?y:z)))
#define GetFinalImage(stringA,stringB)  (IsIphone4?StringFormat(stringA):StringFormat(stringB))
#define StringFormat(a) [NSString stringWithFormat:@"%@",a]

@end

@implementation HBShakeGamesCtrl

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //self.navigationController.delegate = self;
}

-(void)buildLayout{
    [self setTitle:@"摇一摇"];
    
    isStart = NO;
    tool = [[LZAudioTool alloc]init];
    
    [[UIApplication sharedApplication] setApplicationSupportsShakeToEdit:YES];//配置支持摇动
    [self becomeFirstResponder];
    
    [tool bgplayMusic:@"bgmusic.mp3"];

    actRuleArr    = [[NSMutableArray alloc] init];
    childImageArr = [[NSMutableArray alloc] init];
    shakeImageArr = [[NSMutableArray alloc] init];
    orangeArr     = @[self.firstOrange,
                      self.secOrange,
                      self.thirdOrange,
                      self.fourthOrange,
                      self.fifthOrange,
                      self.sixOrange,
                      self.seventhOrange,
                      self.eitOrange];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appBackGround) name:@"backGroud" object:nil];
  
    
    [self creatHomeView];
  
    [self sizeToIPhone];
    
    
}

- (void)sizeToIPhone{

    [self.view layoutIfNeeded];
    NSLayoutConstraint* firstOrangV =[NSLayoutConstraint
                                       constraintWithItem:self.firstOrange
                                       attribute:NSLayoutAttributeTop
                                       relatedBy:NSLayoutRelationEqual
                                       toItem:self.view
                                       attribute:NSLayoutAttributeBottom
                                       multiplier:GetFinalresult(0.048,0.18)
                                       constant:0.0];
    NSLayoutConstraint* firstOrangH =[NSLayoutConstraint
                                      constraintWithItem:self.firstOrange
                                      attribute:NSLayoutAttributeLeft
                                      relatedBy:NSLayoutRelationEqual
                                      toItem:self.view
                                      attribute:NSLayoutAttributeRight
                                      multiplier:GetFinalresult(0.3,0.32)
                                      constant:0.0];
    
    [self.view addConstraint: firstOrangV];
    [self.view addConstraint: firstOrangH];
    
    NSLayoutConstraint* secOrangeV = [NSLayoutConstraint
                                      constraintWithItem:self.secOrange
                                      attribute:NSLayoutAttributeTop
                                      relatedBy:NSLayoutRelationEqual
                                      toItem:self.view
                                      attribute:NSLayoutAttributeBottom
                                      multiplier:GetFinalresult(0.175,0.259)
                                      constant:0.0];
    NSLayoutConstraint* secOrangeH = [NSLayoutConstraint
                                      constraintWithItem:self.secOrange
                                      attribute:NSLayoutAttributeLeft
                                      relatedBy:NSLayoutRelationEqual
                                      toItem:self.view
                                      attribute:NSLayoutAttributeRight
                                      multiplier:GetFinalresult(0.453,0.498)
                                      constant:0.0];
    
    [self.view addConstraint: secOrangeV];
    [self.view addConstraint: secOrangeH];
    
    NSLayoutConstraint* thirdV =[NSLayoutConstraint
                                      constraintWithItem:self.thirdOrange
                                      attribute:NSLayoutAttributeTop
                                      relatedBy:NSLayoutRelationEqual
                                      toItem:self.view
                                      attribute:NSLayoutAttributeBottom
                                      multiplier:GetFinalresult(0.041,0.158)
                                      constant:0.0];
    NSLayoutConstraint* thirdH =[NSLayoutConstraint
                                      constraintWithItem:self.thirdOrange
                                      attribute:NSLayoutAttributeLeft
                                      relatedBy:NSLayoutRelationEqual
                                      toItem:self.view
                                      attribute:NSLayoutAttributeRight
                                      multiplier:GetFinalresult(0.55,0.592)
                                      constant:0.0];
    
    [self.view addConstraint: thirdV];
    [self.view addConstraint: thirdH];
    
    NSLayoutConstraint* fourthV =[NSLayoutConstraint
                                      constraintWithItem:self.fourthOrange
                                      attribute:NSLayoutAttributeTop
                                      relatedBy:NSLayoutRelationEqual
                                      toItem:self.view
                                      attribute:NSLayoutAttributeBottom
                                      multiplier:GetFinalresult(0.264,0.337)
                                      constant:0.0];
    NSLayoutConstraint* foutthH =[NSLayoutConstraint
                                      constraintWithItem:self.fourthOrange
                                      attribute:NSLayoutAttributeLeft
                                      relatedBy:NSLayoutRelationEqual
                                      toItem:self.view
                                      attribute:NSLayoutAttributeRight
                                      multiplier:GetFinalresult(0.078,0.08)
                                      constant:0.0];
    
    [self.view addConstraint: fourthV];
    [self.view addConstraint: foutthH];
    NSLayoutConstraint* fifthV =[NSLayoutConstraint
                                      constraintWithItem:self.fifthOrange
                                      attribute:NSLayoutAttributeTop
                                      relatedBy:NSLayoutRelationEqual
                                      toItem:self.view
                                      attribute:NSLayoutAttributeBottom
                                      multiplier:GetFinalresult(0.30,0.371)
                                      constant:0.0];
    NSLayoutConstraint* fifthH =[NSLayoutConstraint
                                      constraintWithItem:self.fifthOrange
                                      attribute:NSLayoutAttributeLeft
                                      relatedBy:NSLayoutRelationEqual
                                      toItem:self.view
                                      attribute:NSLayoutAttributeRight
                                      multiplier:GetFinalresult(0.18,0.186)
                                      constant:0.0];
    
    [self.view addConstraint: fifthV];
    [self.view addConstraint: fifthH];
    NSLayoutConstraint* sixthV =[NSLayoutConstraint
                                      constraintWithItem:self.sixOrange
                                      attribute:NSLayoutAttributeTop
                                      relatedBy:NSLayoutRelationEqual
                                      toItem:self.view
                                      attribute:NSLayoutAttributeBottom
                                      multiplier:GetFinalresult(0.375,0.427)
                                      constant:0.0];
    NSLayoutConstraint* sixthH =[NSLayoutConstraint
                                      constraintWithItem:self.sixOrange
                                      attribute:NSLayoutAttributeLeft
                                      relatedBy:NSLayoutRelationEqual
                                      toItem:self.view
                                      attribute:NSLayoutAttributeRight
                                      multiplier:GetFinalresult(0.609,0.64)
                                      constant:0.0];
    
    [self.view addConstraint: sixthV];
    [self.view addConstraint: sixthH];
    NSLayoutConstraint* seventhV =[NSLayoutConstraint
                                      constraintWithItem:self.seventhOrange
                                      attribute:NSLayoutAttributeTop
                                      relatedBy:NSLayoutRelationEqual
                                      toItem:self.view
                                      attribute:NSLayoutAttributeBottom
                                      multiplier:GetFinalresult(0.225,0.326)
                                      constant:0.0];
    NSLayoutConstraint* seventhH =[NSLayoutConstraint
                                      constraintWithItem:self.seventhOrange
                                      attribute:NSLayoutAttributeLeft
                                      relatedBy:NSLayoutRelationEqual
                                      toItem:self.view
                                      attribute:NSLayoutAttributeRight
                                      multiplier:GetFinalresult(0.75,0.781)
                                      constant:0.0];
    
    [self.view addConstraint: seventhH];
    [self.view addConstraint: seventhV];
    NSLayoutConstraint* eighthV =[NSLayoutConstraint
                                      constraintWithItem:self.eitOrange
                                      attribute:NSLayoutAttributeTop
                                      relatedBy:NSLayoutRelationEqual
                                      toItem:self.view
                                      attribute:NSLayoutAttributeBottom
                                      multiplier:GetFinalresult(0.427,0.479)
                                      constant:0.0];
    NSLayoutConstraint* eighthH =[NSLayoutConstraint
                                      constraintWithItem:self.eitOrange
                                      attribute:NSLayoutAttributeLeft
                                      relatedBy:NSLayoutRelationEqual
                                      toItem:self.view
                                      attribute:NSLayoutAttributeRight
                                      multiplier:GetFinalresult(0.078,0.08)
                                      constant:0.0];
    
    [self.view addConstraint: eighthV];
    [self.view addConstraint: eighthH];
}

- (void)appBackGround{
    [self.navigationController popToRootViewControllerAnimated:NO];
}
- (void)creatHomeView{
    if (!(IsNotIphone4)) {
        [self.backImage setImage: [UIImage imageNamed:@"shake_背景_4"]];
        UIImage* image1 = [UIImage imageNamed:@"shake_橘子_1@1x"];
        UIImage* image2 = [UIImage imageNamed:@"shake_橘子_2@1x"];
        for (int i =0; i <orangeArr.count; i ++) {
            UIImageView* imageView = orangeArr[i];
            if ((i ==2)||(i ==4)||(i ==6)) {
                imageView.size = image1.size;
                imageView.image = image1;
                LLog(@"向右看%lf,%lf",imageView.size.width,imageView.size.height);
            }else{
                imageView.size = image2.size;
                imageView.image = image2;
                LLog(@"向左看%lf,%lf",imageView.size.width,imageView.size.height);
            }
        }
    }
    
    [self.basicView bringSubviewToFront:self.topTitleView];
    UIImage* gameStartImage = [UIImage imageNamed:@"shake_开始游戏_1"];
    gameStartBtnImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, gameStartImage.size.width, gameStartImage.size.height)];
    NSMutableArray* gameStartArr = [NSMutableArray arrayWithCapacity:2];
    for (int i=1; i <3; i ++) {
        UIImage* image = [UIImage imageNamed:[NSString stringWithFormat:@"%@%d",GetFinalImage(@"shake_gameStartBtn_4_", @"shake_开始游戏_"),i]];
        [gameStartArr addObject:image];
    }
    
    [gameStartBtnImage setCenter:CGPointMake(SCREEN_WIDTH/2, SCREEN_HEIGHT-GetFinalresult(145, 160))];
    gameStartBtnImage.animationImages = gameStartArr;
    gameStartBtnImage.animationDuration = 0.25;
    gameStartBtnImage.animationRepeatCount = 10000;
    [gameStartBtnImage startAnimating];
    
    gameStartBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [gameStartBtn setFrame:CGRectMake(0, 0, gameStartImage.size.width, gameStartImage.size.height)];
    [gameStartBtn setCenter:CGPointMake(SCREEN_WIDTH/2, SCREEN_HEIGHT-GetFinalresult(145, 160))];
    [self.view addSubview:gameStartBtn];
    [gameStartBtn addTarget:self action:@selector(gameStart:) forControlEvents:UIControlEventTouchUpInside];
    
    NSString* actImageName = [NSString stringWithFormat:@"%@",GetFinalImage(@"shake_actRule_4_1", @"shake_活动规则_1")];
    UIImage* actImage = [UIImage imageNamed:actImageName];
    actvRuleImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, actImage.size.width, actImage.size.height)];
    [actvRuleImage setCenter:CGPointMake(SCREEN_WIDTH/2, SCREEN_HEIGHT-GetFinalresult(90, 100))];

    
    for (int i=1; i <3; i++) {
        UIImage* image = [UIImage imageNamed:[NSString stringWithFormat:@"%@%d", GetFinalImage(@"shake_actRule_4_", @"shake_活动规则_"),i]];
        [actRuleArr addObject:image];
    }
    actvRuleImage.animationImages = actRuleArr;
    actvRuleImage.animationDuration = 0.35;
    actvRuleImage.animationRepeatCount = 100000;
    [self.view addSubview:actvRuleImage];
    [actvRuleImage startAnimating];
    
    
    
    UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(activetyDetailAction:)];
    [actvRuleImage addGestureRecognizer:tap];
    [actvRuleImage setUserInteractionEnabled:YES];
    
    
    
    UIImage* botOrangeImage = [UIImage imageNamed:[NSString stringWithFormat:@"%@",GetFinalImage(@"shake_falldown_4_1", @"shake_falldown_5_1")]];
    botOrangeView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, botOrangeImage.size.width, botOrangeImage.size.height)];
    [botOrangeView setCenter:CGPointMake(gameStartBtn.origin.x +gameStartImage.size.width , GetFinalResult(SCREEN_HEIGHT-200,SCREEN_HEIGHT-240,SCREEN_HEIGHT-265, SCREEN_HEIGHT-265))];
    botOrangeView.image = botOrangeImage;
    UIImage* botOrangeShadowImage = [UIImage imageNamed:@"shake_掉下后橘子的影子"];
    botOrangeShadow = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, botOrangeShadowImage.size.width, botOrangeShadowImage.size.height)];
    botOrangeShadow.image = botOrangeShadowImage;
    botOrangeShadow.center = CGPointMake(botOrangeView.center.x-15, botOrangeView.origin.y+botOrangeImage.size.height-5);

    UIImage* shakeImage = [UIImage imageNamed:[NSString stringWithFormat:@"%@",GetFinalImage(@"shake_摇一摇_4_1",@"shake_摇一摇－1")]];
    shakeImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, shakeImage.size.width, shakeImage.size.height)];
    for (int i=1; i <3; i++) {
        UIImage* image =[ UIImage imageNamed:[NSString stringWithFormat:@"%@%d",GetFinalImage(@"shake_摇一摇_4_",@"shake_摇一摇－"),i]];
        [shakeImageArr addObject:image];
    }
    shakeImageView.center = CGPointMake(SCREEN_WIDTH/2, SCREEN_HEIGHT -GetFinalresult(120, 140));
    shakeImageView.animationImages = shakeImageArr;
    shakeImageView.animationDuration = 0.35;
    shakeImageView.animationRepeatCount = 100000;
    shakeImageView.alpha = 0;
    
    [self.view addSubview:shakeImageView];
    [self.view addSubview:botOrangeShadow];
    [self.view addSubview:botOrangeView];
    [self.view addSubview:gameStartBtnImage];
}

- (void)activetyDetailAction:(UITapGestureRecognizer*)tap{
    LLog(@"活动规则");
    isShowRuleView = YES;
    CustomerShakeRule* ruleView = [[CustomerShakeRule alloc] init];
    ruleView.isCancelRuleView = ^(BOOL isCancelRule){
        isCancelRuleView = isCancelRule;
    };
    [ruleView showShakeRule];
}

- (void)tapBackView:(UITapGestureRecognizer*)tap{
    [UIView animateWithDuration:0.35 animations:^{
        backView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);
    } completion:^(BOOL finished) {
        
    }];
}
- (void)gameStart:(UIButton*)button{
    [self startViewDismiss];
}

- (void)startViewDismiss{
    [self.view layoutIfNeeded];
    [UIView animateWithDuration:0.8 animations:^{
        self.topTitleViewLeadingToTop.constant = - 300;
        [gameStartBtn setFrame:CGRectMake(gameStartBtn.frame.origin.x, 760, gameStartBtn.size.width, gameStartBtn.size.height)];
        [gameStartBtnImage setFrame:CGRectMake(gameStartBtn.frame.origin.x, 760, gameStartBtn.size.width, gameStartBtn.size.height)];
        [actvRuleImage setFrame:CGRectMake(actvRuleImage.frame.origin.x, 760, actvRuleImage.size.width, actvRuleImage.size.height)];
        [botOrangeView setFrame:CGRectMake(414, botOrangeView.frame.origin.y, botOrangeView.size.width, botOrangeView.size.height)];
        [botOrangeShadow setFrame:CGRectMake(414, botOrangeShadow.frame.origin.y, botOrangeShadow.size.width, botOrangeShadow.size.height)];
        if (firstShakeCount <2) {
           [shakeImageView setAlpha:1];
        }else{
            [shakeImageView setAlpha:0];
        }
        [self.view layoutIfNeeded];
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        isStart = YES;
        firstShakeCount = 2;
        [self startNormalAnimation];
        [shakeImageView startAnimating];
    });
}

- (void)startNormalAnimation{
    if (shakeCount == 1) {
        orangeArr = nil;
        orangeArr = @[self.firstOrange,self.secOrange,self.fourthOrange,self.fifthOrange,self.sixOrange,self.seventhOrange,self.eitOrange];
    }
    CABasicAnimation* shake = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    shake.fromValue = [NSNumber numberWithFloat:-M_PI/15];
    shake.toValue   = [NSNumber numberWithFloat:+M_PI/15];
    shake.duration = 0.7;
    shake.autoreverses = YES;
    shake.repeatCount = 10000;
    
    for (UIImageView* orangeImage in orangeArr) {
        if (!shakeCount) {
            [CATransaction begin];
            [CATransaction setDisableActions:NO];
            [self setAnchorPoint:CGPointMake(0.5,-0.1) forView:orangeImage withOldFrame:orangeImage.frame];
            [CATransaction commit];
            
        }
        [orangeImage.layer addAnimation:shake forKey:@"shakeAnimation"];
        [UIView animateWithDuration:5.0 delay:0.0
                            options:UIViewAnimationOptionCurveEaseIn | UIViewAnimationOptionAllowUserInteraction
                         animations:^{
                             
                         } completion:nil];
    }
}

- (void) setAnchorPoint:(CGPoint)anchorpoint forView:(UIImageView *)imageView withOldFrame:(CGRect)frame{
    imageView.layer.anchorPoint = anchorpoint;
    imageView.frame = frame;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.navigationController.delegate = self;

    if (shakeCount == 2 ) {
      
    }else{
        shakeImageView.alpha = 0;
    }
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:YES];
    [tool bgstopMusic];
    [tool shakeStop];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{
 
}

- (void)startShake{
    if (firstShakeCount < 2) {
        firstShakeCount += 1;
    }
    LLog(@"%lu",(long)firstShakeCount);
    if (isStart == NO) {
        isStart = YES;
        [self startViewDismiss];
    }
    if (isStart == YES && firstShakeCount == 2) {
        LLog(@"开始摇动手机");
        if (!shakeCount) {
            [shakeImageView stopAnimating];
            [shakeImageView setAlpha:0];
            [tool shakeMusic:@"shake.mp3"];
            [self.thirdOrange setImage:[UIImage imageNamed:@"shake_橘子-2"]];
            CABasicAnimation* shake = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
            shake.fromValue = [NSNumber numberWithFloat:-M_PI/15];
            shake.toValue   = [NSNumber numberWithFloat:+M_PI/15];
            shake.duration = 0.05;
            shake.autoreverses = YES;
            shake.repeatCount = 7;
            
            NSString* imageName1 = [NSString stringWithFormat:@"%@",GetFinalImage(@"shake_橘子_4@1x", @"shake_橘子－3")];
            NSString* imageName2 = [NSString stringWithFormat:@"%@",GetFinalImage(@"shake_橘子_3@1x", @"shake_橘子－4")];
            if (!shakeCount) {
                for (int i=0; i <orangeArr.count; i++) {
                    UIImageView* imageView = orangeArr[i];
                    if ((i == 2)||(i == 4) || (i == 6)) {
                        [imageView setImage:[UIImage imageNamed:imageName1]];
                    }else{
                        [imageView setImage:[UIImage imageNamed:imageName2]];
                    }
                }
            }else if(shakeCount == 1){
                for (int i=0; i <orangeArr.count; i++) {
                    UIImageView* imageView = orangeArr[i];
                    if ((i == 2)||(i == 3) || (i == 5)) {
                        [imageView setImage:[UIImage imageNamed:imageName1]];
                    }else{
                        [imageView setImage:[UIImage imageNamed:imageName2]];
                    }
                }
            }
            for (UIImageView* orangeImage in orangeArr) {
                [self setAnchorPoint:CGPointMake(0.5,-0.1) forView:orangeImage withOldFrame:orangeImage.frame];
                [orangeImage.layer addAnimation:shake forKey:@"shakeAnimation"];
        
            }

            //开始掉落
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.36 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self shakeOrange];
            });
        }
    }
}

- (void)shakeOrange{
    if (isStart == YES) {
        if (!shakeCount ) {
            [tool shakeStop];
            for (int i=0; i <orangeArr.count; i++) {
                UIImageView* imageView = orangeArr[i];
                if ((i == 3)||(i == 5) || (i == 7)) {
                    [imageView setImage:[UIImage imageNamed:@"shake_橘子－2"]];
                }else{
                    [imageView setImage:[UIImage imageNamed:@"shake_橘子－1"]];
                }
            }
            if (firstShakeCount>1) {
                shakeCount = 1;
            }
            [self startNormalAnimation];
        }
        if (firstShakeCount == 2 && isStart == YES) {
            firstShakeCount = 3;
            [shakeImageView setAlpha:0];
            [self animation1];
            [self.thirdOrange stopAnimating];
        }
        
    }

}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{
    if (motion == UIEventSubtypeMotionShake) {
        if (isCancelRuleView == YES) {
            [self startShake];
        }else if(isShowRuleView == NO){
            [self startShake];
        }
    }
    //让震动
//    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    if (event.subtype == UIEventSubtypeMotionShake) {
 
    }
}

- (void)animation1{
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, self.thirdOrange.origin.x, self.thirdOrange.origin.y);
    CGPathAddQuadCurveToPoint(path, NULL, self.thirdOrange.origin.x -100, self.thirdOrange.origin.y -GetFinalresult(150, 200), self.thirdOrange.origin.x -100, GetFinalresult(270, 430));
    
    CAKeyframeAnimation *animate = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    animate.delegate =self;
    animate.fillMode = kCAFillModeForwards;
    animate.repeatCount = 0;
    animate.path = path;
    animate.removedOnCompletion = NO;
    CGPathRelease(path);
    
    //缩放
    CABasicAnimation *resizeAnimation1 = [CABasicAnimation animationWithKeyPath:@"bounds.size"];
    [resizeAnimation1 setToValue:[NSValue valueWithCGSize:CGSizeMake(30.0f, self.thirdOrange.size.height * (30.0f / self.thirdOrange.size.width))]];
    resizeAnimation1.fillMode = kCAFillModeForwards;
    resizeAnimation1.removedOnCompletion = NO;
    
    
    CAAnimationGroup *group = [CAAnimationGroup animation];
    group.fillMode = kCAFillModeForwards;
    group.removedOnCompletion = NO;
    [group setAnimations:[NSArray arrayWithObjects:animate, resizeAnimation1, nil]];
    group.duration = 1.0;
    group.delegate = self;
    [group setValue:self.secOrange forKey:@"imageViewBeingAnimated"];
    [self.thirdOrange.layer addAnimation:group forKey:@"savingAnimation"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        thirdImage = [UIImage imageNamed:[NSString stringWithFormat:@"%@",GetFinalImage(@"shake_falldown_orange_2_1", @"shake_falldown_orange1")]];
        for (int i=0; i<2; i++) {
            UIImage* image = [UIImage imageNamed:[NSString stringWithFormat:@"%@%d",GetFinalImage(@"shake_falldown_orange_2_", @"shake_falldown_orange"),i+1]];
            [childImageArr addObject:image];
        }
        self.thirdOrange.animationImages = childImageArr;
        self.thirdOrange.animationDuration = 0.25;
        self.thirdOrange.animationRepeatCount = 100000;
        self.thirdOrange.userInteractionEnabled = YES;
        [self.thirdOrange setImage:thirdImage];
        [self animation2];
    });
}

- (void)animation2{
    CGMutablePathRef path = CGPathCreateMutable();
    //第一次落地点
    CGPathMoveToPoint(path, NULL, self.thirdOrange.origin.x -GetFinalresult(60, 100), self.thirdOrange.origin.y+GetFinalResult(150,270,300, 300));
    //第二次落地点
    CGPathAddQuadCurveToPoint(path, NULL, self.thirdOrange.origin.x +GetFinalresult(55, -15), GetFinalresult(100, 130), self.thirdOrange.origin.x +GetFinalresult(25, -15), self.thirdOrange.origin.y+GetFinalResult(250,275,310, 310));//
    CAKeyframeAnimation *animate = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    animate.delegate =self;
    animate.fillMode = kCAFillModeForwards;
    animate.repeatCount = 0;
    animate.path = path;
    animate.removedOnCompletion = NO;
    CGPathRelease(path);
    
    //缩放
    CABasicAnimation *resizeAnimation = [CABasicAnimation animationWithKeyPath:@"bounds.size"];
    [resizeAnimation setToValue:[NSValue valueWithCGSize:CGSizeMake(thirdImage.size.width,thirdImage.size.height)]];
    resizeAnimation.fillMode = kCAFillModeForwards;
    resizeAnimation.removedOnCompletion = NO;
    
    CAAnimationGroup *group = [CAAnimationGroup animation];
    group.fillMode = kCAFillModeForwards;
    group.removedOnCompletion = NO;
    [group setAnimations:[NSArray arrayWithObjects:animate, resizeAnimation, nil]];
    group.duration = 0.34;
    group.delegate = self;
    [group setValue:self.secOrange forKey:@"imageViewBeingAnimated"];
    [self.thirdOrange.layer addAnimation:group forKey:@"savingAnimation"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        UIButton* button = [UIButton buttonWithType:UIButtonTypeSystem];
        [button setFrame:CGRectMake(self.thirdOrange.origin.x +GetFinalresult(25, -15), self.thirdOrange.origin.y+GetFinalresult(250, 310), thirdImage.size.width, thirdImage.size.height)];
        [button addTarget:self action:@selector(thirdBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
        [self.thirdOrange startAnimating];
        [self startNormalAnimation];
    });
}

- (void)thirdBtnAction:(UIButton*)button{
    LLog(@"拆开红包");
    orginPoint = button.center;
//    [CustomLoadingView showHudToView:nil];
    [CustomLoadingView showHudToView:self.view];
    [HBGetRedManager requestToGetUserShakeRedWithResult:^(BOOL isSuccess, NSString *msg, NSError *error) {
//        [CustomLoadingView hideHudForView:nil];
        [CustomLoadingView hideHudForView:self.view];
        if (isSuccess)
        {
            [[NSNotificationCenter defaultCenter]postNotificationName:@"upDataForHome" object:nil];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"upIncomeData" object:nil];
            HBShakeResultCtrl *resultCtrl = [[HBShakeResultCtrl alloc]init];
            [self.navigationController pushViewController:resultCtrl animated:YES];
        }
        else
        {
            if (error)
            {
                DISSMISS_ERR([error description]);
            }
            else
            {
                DISSMISS_ERR(msg);
            }
        }
    }];
    
    
}

#pragma mark - navigation delegate

- (id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
                                  animationControllerForOperation:(UINavigationControllerOperation)operation
                                               fromViewController:(UIViewController *)fromVC
                                                 toViewController:(UIViewController *)toVC
{
    if (operation==UINavigationControllerOperationPush)
    {
        if ([fromVC isKindOfClass:[HBShakeGamesCtrl class]])
        {
            ShakePushTransition *pushTransition = [[ShakePushTransition alloc]init];
            LLog(@"orginPoint:%@",NSStringFromCGPoint(orginPoint));
            pushTransition.orginPoint = orginPoint;
            return pushTransition;
        }
        else{
            return nil;
        }
        
    }
    return nil;
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.navigationController.delegate = nil;
}

-(void)doBack{
    [super doBack];
    self.navigationController.delegate = nil;
}
@end
